#!/bin/bash
# Deploy Java Flink Agents Job to Flink Cluster

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

echo "========================================="
echo " Deploying Java Flink Agents Job"
echo "========================================="

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Configuration
JOBMANAGER="flink-java-jobmanager:8081"
JAR_PATH="/opt/flink/usrlib/flink-llm-behavior-analysis-1.0.0.jar"
MAIN_CLASS="com.citro.agents.BehaviorAnalysisJob"

echo ""
echo "Step 1: Checking if Flink cluster is running..."
if ! docker ps | grep -q "browse-etl-flink-java-jobmanager"; then
    echo -e "${RED}❌ Flink Java cluster is not running${NC}"
    echo "Please start it first with:"
    echo "  docker-compose --profile flink-java up -d"
    exit 1
fi
echo -e "${GREEN}✅ Flink Java cluster is running${NC}"

echo ""
echo "Step 2: Waiting for JobManager to be ready..."
max_wait=30
wait_time=0
while ! docker exec browse-etl-flink-java-jobmanager curl -s http://localhost:8081/overview >/dev/null 2>&1; do
    if [ $wait_time -ge $max_wait ]; then
        echo -e "${RED}❌ JobManager failed to start within ${max_wait}s${NC}"
        exit 1
    fi
    echo "Waiting... ($wait_time/$max_wait)"
    sleep 2
    wait_time=$((wait_time + 2))
done
echo -e "${GREEN}✅ JobManager is ready${NC}"

echo ""
echo "Step 3: Checking Kinesis stream availability..."
max_wait=30
wait_time=0
while ! docker exec browse-etl-localstack awslocal kinesis describe-stream --stream-name click-events-stream --region us-east-1 >/dev/null 2>&1; do
    if [ $wait_time -ge $max_wait ]; then
        echo -e "${RED}❌ Kinesis stream not ready within ${max_wait}s${NC}"
        exit 1
    fi
    echo "Waiting for Kinesis stream... ($wait_time/$max_wait)"
    sleep 2
    wait_time=$((wait_time + 2))
done
echo -e "${GREEN}✅ Kinesis stream 'click-events-stream' is ready${NC}"

echo ""
echo "Step 4: Checking PostgreSQL table (user_behaviors)..."
# 检查表是否存在（不创建，使用现有表）
TABLE_EXISTS=$(docker exec browse-etl-postgres psql -U postgres -d behavior_analysis -tAc \
    "SELECT COUNT(*) FROM information_schema.tables WHERE table_name='user_behaviors';")

if [ "$TABLE_EXISTS" -eq "1" ]; then
    echo -e "${GREEN}✅ Table 'user_behaviors' exists${NC}"
else
    echo -e "${RED}❌ Table 'user_behaviors' does not exist${NC}"
    echo "Please run: make init-db"
    exit 1
fi

echo ""
echo "Step 5: Submitting Flink job..."
docker exec browse-etl-flink-java-jobmanager \
    /opt/flink/bin/flink run \
    -c $MAIN_CLASS \
    -d \
    $JAR_PATH

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✅ Job submitted successfully${NC}"
else
    echo -e "${RED}❌ Job submission failed${NC}"
    exit 1
fi

echo ""
echo "========================================="
echo " Deployment Complete! 🎉"
echo "========================================="
echo ""
echo "📊 Flink Web UI: http://localhost:8082"
echo "🗄️  Database table: user_behaviors (shared with Python processor)"
echo ""
echo "Useful commands:"
echo "  # View job list"
echo "  docker exec browse-etl-flink-java-jobmanager /opt/flink/bin/flink list"
echo ""
echo "  # View logs"
echo "  docker logs browse-etl-flink-java-taskmanager"
echo ""
echo "  # Cancel job"
echo "  docker exec browse-etl-flink-java-jobmanager /opt/flink/bin/flink cancel <JOB_ID>"
echo ""
echo "  # Check results (filter by Java processor)"
echo "  docker exec browse-etl-postgres psql -U postgres -d behavior_analysis -c \"SELECT * FROM user_behaviors WHERE analysis_method LIKE '%java%' ORDER BY created_at DESC LIMIT 10;\""
echo ""
echo "  # Check all results"
echo "  docker exec browse-etl-postgres psql -U postgres -d behavior_analysis -c 'SELECT * FROM user_behaviors ORDER BY created_at DESC LIMIT 10;'"
echo ""
